package me.zhengjie.modules.sync.processing;

import com.alibaba.fastjson.JSON;
import com.qiaofang.applet.common.constant.SyncTypeEnum;
import com.qiaofang.applet.service.other.domain.SignContact;
import com.qiaofang.applet.service.other.service.SignContactService;
import com.qiaofang.applet.service.property.domain.SyncDataQueue;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.sync.ProcessingBase;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/*
 *  电子合同数据处理
 * */
@Slf4j
@Service
public class SignSyncProcessing extends ProcessingBase {

    public SignSyncProcessing() {
        setDataType(SyncTypeEnum.SIGN.getSyncType());
    }

    @Autowired
    SignContactService signContactService;

    @Override
    protected void processing(SyncDataQueue syncDataQueue) {
        String batchContent = syncDataQueue.getBatchContent();
        List<SignContact> list = JSON.parseArray(batchContent, SignContact.class);
        if (null == list) {
            log.info("processing SignContact is null");
            return;
        }
        list.stream().forEach(item -> {
            saveSignContact(item, syncDataQueue);
        });
    }

    private void saveSignContact(SignContact item, SyncDataQueue syncDataQueue) {
        String signatoriesUuid = item.getSignatoriesUuid();
        String companyUuid = syncDataQueue.getCompanyUuid();
        SignContact signContact = signContactService.findBySignatoriesUuidAndCompanyUuid(signatoriesUuid, companyUuid);
        if (!Objects.isNull(item.getDeleted()) && item.getDeleted()) {
            if (!Objects.isNull(signContact)) {
                signContactService.deleteById(signContact.getId());
            }
            return;
        }
        if (Objects.isNull(signContact)) {
            signContact = new SignContact();
        }
        //复制属性
        String[] ignoreProperties = new String[]{"id", "createBy", "updateBy", "createTime", "updateTime"};
        BeanUtils.copyProperties(item, signContact, ignoreProperties);
        signContact.setCompanyUuid(syncDataQueue.getCompanyUuid());
        signContact.setCityCode(syncDataQueue.getCityCode());
        signContact.setCorporationCode(syncDataQueue.getCorporationCode());
        signContact.setUpdateTime(new Date());
        signContact.setLastSyncDate(new Date(System.currentTimeMillis() - DateUtil.DAY_MILLISECONDS));
        try {
            signContactService.save(signContact);
        } catch (Exception e) {
            log.error("saveSignContact error ", e);
            //记录错误日志
            this.saveErrorLog(JSON.toJSONString(signContact), e.getMessage(), syncDataQueue);
        }
    }
}
